package com.wds.common.config;


import com.wds.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-10-11 18:18
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)  //启用权限校验所用的注解
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter authenticationFilter;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    // 使用 BCryptPasswordEncoder
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    //将 AuthenticationManager注入到 IOC容器
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                // 使用 antMatchers控制访问接口
                .and().authorizeRequests()
                // 接口只允许匿名访问
                .antMatchers("/user/login"
                ).anonymous()
                // 接口全部允许访问
                .antMatchers("/"

                ).permitAll()
                // 其余全部认证后才能访问
                .anyRequest().authenticated()

                .and().logout().disable()

                //Security 允许跨域
                .cors().and()

                //将Jwt过滤器添加到过滤器链中
                .addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class)
                // 自定义认证失败的异常处理
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
        ;

    }


}
